package com.tdw.filter;

import java.io.IOException;
import java.io.PrintWriter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import com.tdw.util.ThreadUtils;
import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

/**
 * @description ErrorFilter
 * @author TDW
 * @date 2016年12月29日
 *
 */
public class ErrorFilter extends ZuulFilter {

	//private static final Logger log = LoggerFactory.getLogger(ErrorFilter.class);
	private static final Logger logger = LoggerFactory.getLogger(ErrorFilter.class);

	public boolean shouldFilter() {
		return true;
	}

	/**
	 * System err process
	 */
	public Object run() {
		final Throwable e = RequestContext.getCurrentContext().getThrowable();
		Throwable cause = e.getCause();
		logger.error("Exception was thrown in filters: ", e);
		logger.error("Exception was thrown in filters: ", cause);

		ThreadUtils.invoke(new Runnable() {

			public void run() {
				StringBuffer buffer = new StringBuffer();
				if(e != null)
				buffer.append("<b>" + e.getClass().getName() + ": ");
				buffer.append(e.getMessage());
				buffer.append("</b>");
				buffer.append("<br>");
				StackTraceElement[] trace = e.getStackTrace();
				if (trace != null && trace.length > 0)
					for (StackTraceElement s : trace) {
						buffer.append("&nbsp;&nbsp;&nbsp;&nbsp;at ").append(s).append("<br>");
					}
				
				//cause
				Throwable cause = e.getCause();
				if(cause != null){
					trace = cause.getStackTrace();
					buffer.append("<b>" + cause.getClass().getName() + ": ");
					buffer.append(cause.getMessage());
					buffer.append("</b>");
					buffer.append("<br>");
					if (trace != null && trace.length > 0)
						for (StackTraceElement s : trace) {
							buffer.append("&nbsp;&nbsp;&nbsp;&nbsp;at ").append(s).append("<br>");
						}
				}
				//EmailSender.sendSystemException(buffer.toString());
			}
		});
		//其它异常返回处理
		// return new ModelAndView("404");
		// return new ModelAndView("500");
		// return new ModelAndView("error");
		PrintWriter out = null;
		try {
			out = RequestContext.getCurrentContext().getResponse().getWriter();
		} catch (IOException e1) {
			logger.error("获取输出流异常",e);
		}
		JSONObject json = new JSONObject();
        json.put("ret_code", "9999");
        json.put("ret_msg", "system err");//系统异常
        out.write(json.toJSONString());
        out.close();
        return json.toJSONString();
	}

	
	public String filterType() {
		return "error";
	}

	
	public int filterOrder() {
		return 1;
	}

}
